package com.wcity.manage.service.impl;

import com.wcity.manage.common.context.Constants;
import com.wcity.manage.common.utils.AuthUtil;
import com.wcity.manage.common.utils.StringUtil;
import com.wcity.manage.dao.mapper.*;
import com.wcity.manage.dao.model.*;
import com.wcity.manage.service.AuthService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 鉴权服务层
 *
 * @author dy
 * @modify jn
 */
@Service
public class AuthServiceImpl implements AuthService {

    public String checkAuth(User user, String actName ) {

        if ( StringUtil.isBlank( actName ) ) return "invalid act";
        // 请求act是否存在
        Act act = actMapper.findByActName( actName.substring( 1, actName.length() ) );
        if ( act == null ) return "invalid act";
        // 用户角色
        if ( user.getRole() == null ) return "未分配角色";
        // 判断是否有权限操作
        if ( !AuthUtil.auth( act.getAuthId(), user.getRole() ) ) return "没有权限";
        return "";
    }

    @Override
    public String checkToken(String token, String registerId) {

        if ( StringUtil.isBlank( token ) || !StringUtil.isNumeric( registerId ) )
            return Constants.TOKEN_ERROR;

        TokenHistory history = new TokenHistory();
        history.setRegisterId( Integer.parseInt( registerId ) );
        history.setToken( token );
        // 判断是否其他设备登陆
        int historyLogin = historyMapper.count( history );
        if ( historyLogin > 0 ) return Constants.TOKEN_EXPIRE_ERROR;

        // 用户查询
        Register t = registerMapper.findToken( Integer.parseInt( registerId ), token );

        if ( t == null ) return Constants.TOKEN_ERROR;

        if ( t.getBlockId() <= 0 ) return "未入住任何小区";

        // 项目状态检查
        Block block = t.getBlock();
        if ( block == null ) return "该小区尚未入住";
        ModuleManage manage = manageMapper.findByUserId( block.getUserId() );
        if ( manage == null ) return "用户配置不存在";
        if ( manage.getStatus() != 1 ) return "该小区尚未入住";

//        long tokenTime = t.getExpireTime().getTime();
//        long current = System.currentTimeMillis();
        // 不设置token过期
//        if ( current - tokenTime > Constants.TOKEN_EXPIRE_TIME ) return Constants.TOKEN_EXPIRE_ERROR;

        return "";
    }

    @Resource private ActMapper actMapper;
    @Resource private RegisterMapper registerMapper;
    @Resource private ModuleManageMapper manageMapper;
    @Resource private TokenHistoryMapper historyMapper;

}
